package cn.cj.erp.modules.monitor.controller;

import cn.cj.erp.common.vo.TableData;
import cn.cj.erp.common.vo.monitor.SysUserOnlineVo;
import cn.cj.erp.common.enums.LogBusinessTypeEnum;
import cn.cj.erp.common.http.Result;
import cn.cj.erp.common.redis.RedisCache;
import cn.cj.erp.common.redis.RedisKeyEnum;
import cn.cj.erp.common.security.annotation.Log;
import cn.cj.erp.common.security.security.user.LoginUser;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.*;

/**
 * 在线用户监控
 *
 * @author chenjian
 */
@Slf4j
@RestController
@RequestMapping("/monitor/online")
public class SysUserOnlineController {
    @Resource
    private RedisCache redisCache;

    @PreAuthorize("@ss.hasPerm('monitor:online:list')")
    @GetMapping("/list")
    public Result<TableData> list(String ip, String username) {
        Set<String> keys = redisCache.keys(RedisKeyEnum.LOGIN_TOKEN.getKey("*"));
        List<SysUserOnlineVo> userOnlineList = new ArrayList<>();
        for (String key : keys) {
            LoginUser user = redisCache.get(key, LoginUser.class);
            if (StrUtil.isNotEmpty(ip) && StrUtil.isNotEmpty(username)) {
                // 输入IP地址和用户名
                if (StrUtil.equals(ip, user.getIp()) && StrUtil.equals(username, user.getUsername())) {
                    userOnlineList.add(SysUserOnlineVo.newInstance(user));
                }
            }
            if (StrUtil.isNotEmpty(ip)) {
                // 仅输入IP地址
                if (StrUtil.equals(ip, user.getIp())) {
                    userOnlineList.add(SysUserOnlineVo.newInstance(user));
                }
            } else if (StrUtil.isNotEmpty(username)) {
                // 仅输入用户名
                if (StrUtil.equals(username, user.getUsername())) {
                    userOnlineList.add(SysUserOnlineVo.newInstance(user));
                }
            } else {
                // 什么都没有输入
                userOnlineList.add(SysUserOnlineVo.newInstance(user));
            }
        }
        Collections.reverse(userOnlineList);
        for (SysUserOnlineVo sysUserOnlineVo : userOnlineList) {
            sysUserOnlineVo.hide();
        }
        return Result.ok(TableData.newInstance(userOnlineList));
    }

    /**
     * 强退用户
     */
    @PreAuthorize("@ss.hasPerm('monitor:online:forceLogout')")
    @Log(title = "在线用户", businessType = LogBusinessTypeEnum.FORCE)
    @PostMapping("/forceLogout/{userId}")
    public Result<Boolean> forceLogout(@PathVariable String userId) {
        redisCache.delete(RedisKeyEnum.LOGIN_TOKEN.getKey(userId));
        return Result.ok(true);
    }
}
